package com.edu.base.ums.umsMember.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.edu.base.common.SystemService;
import com.edu.base.common.utils.IdGen;
import com.edu.base.common.utils.IdWorker;
import com.edu.base.common.vo.VerifyCodeEnum;
import com.edu.base.rest.AppBackUserLoginController;
import com.edu.base.rest.service.AppLoginService;
import com.edu.base.ums.umsMember.domain.UmsMember;
import com.edu.base.ums.umsMember.mapper.UmsMemberRyMapper;
import com.edu.base.ums.umsMember.service.IUmsMemberRyService;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.UUIDUtils;
import com.ruoyi.common.utils.uuid.IdUtils;

/**
 * 会员Service业务层处理
 * 
 * @author lzs
 * @date 2021-02-21
 */
@Service 
public class UmsMemberRyServiceImpl implements IUmsMemberRyService 
{
    @Autowired
    private UmsMemberRyMapper umsMemberRyMapper;
    
	@Autowired
	private RedisCache redisCache;
	
	@Autowired
	private AppLoginService  appLoginService;

    /**
     * 查询会员
     * 
     * @param id 会员ID
     * @return 会员
     */
    @Override 
    public UmsMember selectUmsMemberRyById(Long id)
    {
        return umsMemberRyMapper.selectUmsMemberRyById(id);
    }

    /**
     * 查询会员列表
     * 
     * @param umsMemberRy 会员
     * @return 会员
     */
    @Override 
    public List<UmsMember> selectUmsMemberRyList(UmsMember umsMemberRy)
    {
        return umsMemberRyMapper.selectUmsMemberRyList(umsMemberRy);
    }

    /**
     * 新增会员
     * 
     * @param umsMemberRy 会员
     * @return 结果
     */
    @Override 
    public int insertUmsMemberRy(UmsMember umsMemberRy)
    {
        umsMemberRy.setCreateTime(DateUtils.getNowDate());
        return umsMemberRyMapper.insertUmsMemberRy(umsMemberRy);
    }

    /**
     * 修改会员
     * 
     * @param umsMemberRy 会员
     * @return 结果
     */
    @Override 
    public int updateUmsMemberRy(UmsMember umsMemberRy)
    {
        return umsMemberRyMapper.updateUmsMemberRy(umsMemberRy);
    }

    /**
     * 批量删除会员
     * 
     * @param ids 需要删除的会员ID
     * @return 结果
     */
    @Override 
    public int deleteUmsMemberRyByIds(Long[] ids)
    {
        return umsMemberRyMapper.deleteUmsMemberRyByIds(ids);
    }

    /**
     * 删除会员信息
     * 
     * @param id 会员ID
     * @return 结果
     */
    @Override 
    public int deleteUmsMemberRyById(Long id)
    {
        return umsMemberRyMapper.deleteUmsMemberRyById(id);
    }
    
    /**
     *激活码样式：LEW开头，10位数字+1个字母（数字和字母不要出现0和O），输入的激活码的时候不分字母大小写，但是后台生成的时候字母需要大写</div><div>后台生成激活码的时候需要激活码以及链接
     * @param length 需要的数字部分的长度
     * @return 返回随机字母数字组合字符串
     */
    @Override 
	public String genSeqNo(int length, String applicationScopeType) {
		String start = "LEW";
		String val = "";
		if ("2".equals(applicationScopeType)) {// 教师激活码用 LEWT 开头
			length = 9;
			start = "LEWT";
		}
		Random random = new Random();
		int index = 0;
		while (index < length) {
			int RandomNum = random.nextInt(10);
			while (RandomNum == 0) {
				RandomNum = random.nextInt(10);
			}
			val = val + RandomNum;
			index++;
		}

		String zimu = String.valueOf((char) (random.nextInt(26) + 65));
		while (zimu.equals("O")) {
			zimu = String.valueOf((char) (random.nextInt(26) + 65));
		}
		return start + val + zimu;
	}
    
    private String qrCode(String id) {
        String url = id; 
        return url;
    }
    
    @Override
    public UmsMember checkThirdPartyBindingUser(String thirdType,String thirdPartyId ) {
		UmsMember umsMember = new UmsMember();
		umsMember.setDelFlag("0");
		umsMember = this.setThirdValue(umsMember, thirdType, thirdPartyId);
		List<UmsMember> clsMemberList = umsMemberRyMapper.selectUmsMemberRyList(umsMember);
		if (null != clsMemberList && clsMemberList.size() > 0) {
			return clsMemberList.get(0);
		} else {
			return null;
		}
	}
    
	/**
	 * @Description：主要用于根据第三方类型来存对应的字段值
	 * @since: 2018年9月6日 下午1:53:59
	 */
	private UmsMember setThirdValue(UmsMember umsMember, String thirdType, String thirdPartyId) {
		if (VerifyCodeEnum.WECHAT_BIND.getMessType().equals(thirdType)) {// 第三方类型为微信时
			umsMember.setWeixinOpenid(thirdPartyId);
		} else if (VerifyCodeEnum.WEIBO_BIND.getMessType().equals(thirdType)) {// 第三方类型为微博时
			umsMember.setBlogToken(thirdPartyId);
		} else if (VerifyCodeEnum.QQ_BIND.getMessType().equals(thirdType)){// 第三方类型为qq时
			umsMember.setQqToken(thirdPartyId);
		}else{//// 第三方类型为苹果
			umsMember.setAppleId(thirdPartyId);
		}
		return umsMember;
	}
	
	/**
	 * @Description：已经绑定过的第三方直接登陆
	 * @author: liujintao
	 * @since: 2018年9月6日 下午2:49:19
	 * @param appUser
	 *            用户对象
	 */
	@Override
	public Map<String, Object> bindingLoginSetToken(UmsMember umsMember) {
		Map<String, Object> dataMap = new HashMap<String, Object>();
		String uuid = IdUtils.simpleUUID();
		String token = appLoginService.login(umsMember.getUsername(), umsMember.getPassword(), uuid);
		// 将用户的token保存到缓存中，key为用户id，vlue为token
		redisCache.setCacheObject(String.valueOf(umsMember.getId()), token, 15 * 24 * 60 * 60,TimeUnit.SECONDS); 
        UmsMember umsMember1 = umsMemberRyMapper.selectUmsMemberRyById(umsMember.getId());
        dataMap.put("memberType", umsMember1.getMemberType());
        dataMap.put("id", umsMember.getId());
		dataMap.put("tokenId", token);
		return dataMap;
	}
	
	// -----------------------------------------------------------------------二级方法----------------------------------------------------------------
		/**
		 * @Description： 用户绑定第三方/绑定第三方并注册
		 * 
		 * @author: liujintao
		 * @since: 2018年9月6日 下午1:48:31
		 * @param mobile    手机号
		 * @param thirdPartyId  第三方id
		 * @param loginType    第三方登录类型
		 * @param nickName   昵称 (第三方)
		 * @param headPortrait   头像(第三方)
		 */
		@Transactional(readOnly = false,rollbackFor=Exception.class)
		@Override
		public UmsMember userBindingThirdParty(String thirdPartyId,String phone,String thirdType,
				String passWord,String nickName,String icon) {
			//String thirdPartyId = params.getDynaValue("thirdPartyId",String.class);// 第三方id
			//String phone = params.getDynaValue("phone",String.class);// 手机号
			//String thirdType = params.getDynaValue("thirdType",String.class);//绑定类型，目前是微信、qq、微博
			//String passWord = params.getPassword();
			//UmsMember exist = umsMemberService.findUserByPhone(phone);// 根据手机号获取用户
			List<UmsMember> umsMemberList = umsMemberRyMapper.getUmsPhoneOrUserName(phone, null);
			if (CollectionUtils.isNotEmpty(umsMemberList)) {// 如果用户不为空,则已有用户 仅需要将第三方和用户绑定即可
				UmsMember exist = umsMemberList.get(0);
	            exist = this.setThirdValue(exist, thirdType, thirdPartyId);// 存入第三方id
	            exist.setNickName(nickName);// 第三方昵称
	            exist.setIcon(icon);// 第三方头像
	            //exist.setPassword(systemService.entryptPassword(passWord));//密码
	            umsMemberRyMapper.updateUmsMemberRy(exist);// 保存修改
				return exist;
			} else {// 用户为空,则为新用户注册并绑定密码
				UmsMember newUser = new UmsMember();
				newUser.setId(IdWorker.idAutoIncrement());
				if(StringUtils.isEmpty(newUser.getIcon()))newUser.setIcon(AppBackUserLoginController.defautPhotoUrlStudent);
				newUser.setStatus("1");
				newUser.setSourceType(1);
				this.setThirdValue(newUser, thirdType, thirdPartyId);
				newUser.setPhone(phone);
				newUser.setStatus("1");
				newUser.setIntegration(0L);
				newUser.setBlance(new BigDecimal(0));
				newUser.setPassword(SystemService.entryptPassword(passWord));
				newUser.setLoginTime(new Date());
				umsMemberRyMapper.insertUmsMemberRy(newUser);
				return newUser;
			}

		}

	@Override
	public void insertUmsMemberRyByPHone(String phone) {
		UmsMember umsMember = new UmsMember();
		umsMember.setId(IdWorker.idAutoIncrement());
		umsMember.setStatus("1");
		umsMember.setMemberType("4");
		umsMember.setIntegration(0L);
		umsMember.setBlance(new BigDecimal(0));
		umsMember.setSourceType(1);
		umsMember.setCreateTime(new Date());
		umsMember.setUsername(IdGen.getUserName(phone));
		umsMember.setPassword(SystemService.entryptPassword("123456"));// 默认密码
		umsMember.setNickName("游客");
		umsMemberRyMapper.insertUmsMemberRy(umsMember);
	}
		
		
	/*	@Override
		public void updateBindingMobileAfterSave(UmsMember umsMember) {
			// TODO Auto-generated method stub
			//需要判断这个用户是否是教师角色。如果是教师角色，需要更新一下系统表的密码
			if(umsMember.getMemberType().equals("2")){
				if(StringUtils.isBlank(umsMember.getNickName())){//说明系统用户登录名还是手机号
					ClsMemberTeacher clsMemberTeacher = (ClsMemberTeacher) service(ClsMemberTeacher.class).findUniqueByPropertyCamel(ClsMemberTeacher._memberId, umsMember.getId());
				    if(clsMemberTeacher!=null&&StringUtils.isNotBlank(clsMemberTeacher.getUserId())){
				    	User user = (User) service(User.class).get(clsMemberTeacher.getUserId());
				    	user.setLoginName(umsMember.getPhone());
				    	user.setPhone(umsMember.getPhone());
				    	service(User.class).save(user);
				    }
				}
			}
		}*/
	 
	
}
